<template>
  <div class="department-container">
    <div class="app-container">
      <!--  -->
      <PageTools>
        <template #left>
          <span>本页数据 {{ total }}条</span>
        </template>

        <template slot="right">
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >导入excel</el-button>
          <el-button
            type="danger"
            size="small"
            @click="hExportExcel"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>

      <!-- //数据页 -->
      <el-card style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />

          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formOfEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" prop="" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :total="total"
            :page-size="pageParams.size"
            layout="prev, pager, next"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>

    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close="hClose"
    >
      <addorEdit
        ref="redAdd"
        @close="showDialog = false"
        @update-empolyee="hUpdateEmpolyee"
      />
    </el-dialog>

    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :visible.sync="showDialogRole"
    >
      <AssignRole
        v-if="showDialogRole"
        :employee-id="curEmployeeId"
        @close="showDialogRole=false"
        @update-close="hUpdateClose"
      />
    </el-dialog>

  </div>
</template>

<script>
import { getEmployeeList, delEmployee, addEmployee } from '@/api/employees' // 获取/删除/新增员工信息
import EmployeeEnum from '@/constant/employees' // 导入枚举状态码-聘用形式
import addorEdit from './empDialog' // 引入添加员工信息
import AssignRole from './assignRole'
// 将状态码数组转对象进行优化, 相比find查找不需重复执行
const hireType = {}
EmployeeEnum.hireType.forEach((item) => {
  hireType[item.id] = item.value
})
// console.log(EmployeeEnum)// 通过打印枚举找到对应的元素
export default {

  components: { // 新增员工的组件
    addorEdit: addorEdit,
    AssignRole
  },

  data() {
    return {
      list: [], // 加载员工信息
      total: 0,
      pageParams: {
        page: 1,
        size: 8
      },
      curEmployeeId: '', // 要分配角色的id
      showDialog: false,
      showDialogRole: false// 分配角色的弹窗
    }
  },

  created() {
    this.loadEmployeeList()
  },

  methods: {
    async loadEmployeeList() { // 加载员工信息
      try {
        const res = await getEmployeeList(this.pageParams)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        this.$message.err('加载员工数据失败')
      }
    },

    async doAdd() { // 执行添加
      try {
        const res = await addEmployee(this.list)// ??
        console.log(res)
        this.$message.success('添加成功')
        this.$emit('close')
      } catch (err) {
        this.$message.error('增加失败')
      }
    },

    async doDel(id) { // 执行删除
      try {
        await delEmployee(id)
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        this.loadEmployeeList()
      } catch (err) {
        this.$message.error('删除失败')
      }
    },

    hDel(id) { // 删除事件
      this.$confirm('确认删除吗?')
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {
          this.$message.error('已取消删除')
        })
    },

    formOfEmployment(id) { // 枚举(聘用)
      return hireType[id]
      //   const res = EmployeeEnum.hireType.find(item => item.id === id)
      //   return res.value
    },

    hCurrentChange(curPage) { // 分页事件
      this.pageParams.page = curPage
      this.loadEmployeeList()
    },

    hUpdateEmpolyee() {
      this.showDialog = false
      this.loadEmployeeList()
    },

    hClose() { // 重置表单
      this.$refs.redAdd.resetForm()
    },

    async hExportExcel() { // 导出表单
      // 1. 获取到具体真实数据
      const res = await getEmployeeList(this.pageParams)
      console.log('有效数据', res.data.rows)
      // 2.处理数据
      const obj = this.transData(res.data.rows)
      // 2. 导出
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: obj.header,
          data: obj.data,
          filename: 'employees-list', // 文件名称
          autoWidth: true, // 自适应宽度
          bookType: 'xlsx'// 文件类型
        })
        //   this.downloadLoading = false
      })
    },
    transData(rows) { // 转换数据
      const map = { // 提前准备的映射关系
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const enKeys = Object.keys(rows[0])
      const header = enKeys.map(enKeys => {
        return map[enKeys]
      })
      const data = rows.map(obj => {
        return Object.values(obj)
      })
      return { header, data }
    },

    hAssignRole(id) { // 点击事件--分配角色
      this.showDialogRole = true
      this.curEmployeeId = id// 点击哪个角色 获取哪个角色ID
    },

    hUpdateClose() { // 分配角色成功
      this.showDialogRole = false
      this.loadEmployeeList()
      this.$message.success('分配角色成功')
    }

  }
}
</script>
